package fy.input.controller;

import java.io.ByteArrayInputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.authenticate.domain.User;
import com.seeyon.ctp.common.controller.BaseController;

import fy.form.listen.dao.MyOrgManager;
import fy.input.conf.InputConfManager;
import fy.input.dao.BudgetCostCountDao;
import fy.input.dao.BudgetCostNumberDao;
import fy.input.service.ZcExcelView;
import fy.input.sql.MySQLSetManager;
import fy.util.MyUtil;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class FyInputController extends BaseController {

    // private final static String managerJSP =
    // "plugin/oaCommonInputExtend/manager";
    private static final String jsonJSP = "fy_view/oa2uap/fillForm/JSON";

    private static final String errorJSP = "fy_view/error";

    public ModelAndView getManagerJSP(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView mav = null;

        if (AppContext.getCurrentUser() != null) {
            String extendParam = request.getParameter("extendParam");
            // response.sendRedirect("../fy_view/oa2hr/inputExtend/reinstatement/reinstatement.html");
            mav = new ModelAndView(("redirect:" + InputConfManager
                    .getInstance().getURL(extendParam)));// InputConfManager.getInstance().getURL(extendParam));
        } else {
            mav = new ModelAndView(errorJSP);
            mav.addObject("title", "错误");
            mav.addObject("msg", "您还未登录，登录后才可以访问此链接");
        }
        return mav;
    }

    // public ModelAndView getManagerJSP2(HttpServletRequest request,
    // HttpServletResponse response) throws Exception {
    // ModelAndView mav = new ModelAndView(managerJSP);
    //
    // if (this.getCurrentUser() != null) {
    // mav.addObject("isLogin", "true");
    // mav.addObject("operate", 2);
    // mav.addObject("urlMap", InputConfManager.getInstance().toString());
    // } else {
    // mav.addObject("isLogin", "false");
    // }
    // return mav;
    // }
    // public ModelAndView getManagerJSP3(HttpServletRequest request,
    // HttpServletResponse response) throws Exception {
    // ModelAndView mav = new ModelAndView(managerJSP);
    //
    // if (this.getCurrentUser() != null) {
    // mav.addObject("isLogin", "true");
    // mav.addObject("operate", 3);
    // mav.addObject("urlMap", InputConfManager.getInstance().toString());
    // } else {
    // mav.addObject("isLogin", "false");
    // }
    // return mav;
    // }
    // public ModelAndView getManagerJSP4(HttpServletRequest request,
    // HttpServletResponse response) throws Exception {
    // ModelAndView mav = new ModelAndView(managerJSP);
    //
    // if (this.getCurrentUser() != null) {
    // mav.addObject("isLogin", "true");
    // mav.addObject("operate", 4);
    // mav.addObject("urlMap", InputConfManager.getInstance().toString());
    // } else {
    // mav.addObject("isLogin", "false");
    // }
    // return mav;
    // }
    // public ModelAndView getFillJSP(HttpServletRequest request,
    // HttpServletResponse response) throws Exception {
    // ModelAndView mav = new ModelAndView(managerJSP);
    //
    // if (this.getCurrentUser() != null) {
    // mav.addObject("isLogin", "true");
    // mav.addObject("urlMap", InputConfManager.getInstance().toString());
    // } else {
    // mav.addObject("isLogin", "false");
    // }
    // return mav;
    // }
    // *************************自定义插件**********************************************
    /**
     * 资本性支出预算导入审批表导入操作
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView doZiBenImport(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        PrintWriter out = response.getWriter();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
                .getFile("file");

        ByteArrayInputStream iais = new ByteArrayInputStream(file.getBytes());
        Workbook book = Workbook.getWorkbook(iais);

        Sheet sheet = book.getSheet(0);
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>资本性支出预算导入审批表</title><script type=\"text/javascript\" src=\"./apps_res/myInputExtend/js/zbxzcys.js\"></script></head><body>");

        out.print("<script type=\"text/javascript\">var data=");

        System.out.println(sheet.getRows());

        JSONArray ja = new JSONArray();
        for (int i = 1, length = sheet.getRows(); i < length; i++) {
            if ("".equals(sheet.getCell(0, i).getContents())) {
                break;
            }
            JSONObject jo = new JSONObject();
            jo.put("number", sheet.getCell(0, i).getContents());
            jo.put("dept", sheet.getCell(1, i).getContents());
            jo.put("dept_child", sheet.getCell(2, i).getContents());
            jo.put("name", sheet.getCell(3, i).getContents());
            jo.put("cost", sheet.getCell(4, i).getContents());
            ja.put(jo);
            jo = null;
        }
        out.print(ja.toString());

        ja = null;

        book.close();
        iais.close();
        iais = null;
        sheet = null;
        book = null;
        file = null;
        multipartRequest = null;
        out.println("; writeToForm();</script>");
        out.println("</body></html>");
        out.flush();
        out.close();
        out = null;
        return null;
    }

    /**
     * 用于EXCEL导入
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView excelImport(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("utf-8");

        PrintWriter out = response.getWriter();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest
                .getFile("file");
        ByteArrayInputStream iais = new ByteArrayInputStream(file.getBytes());
        Workbook book = Workbook.getWorkbook(iais);

        Sheet sheet = book.getSheet(0);
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>导入</title><script type=\"text/javascript\" src=\"./myInputExtend/js/excelImport.js\"></script></head><body>");

        out.print("<script type=\"text/javascript\">var data=");

        // System.out.println(sheet.getRows());
        JSONArray ja = new JSONArray();
        for (int i = 1, length = sheet.getRows(); i < length; i++) {

            Cell[] row = sheet.getRow(i);
            JSONArray rowArray = new JSONArray();
            for (int j = 0; j < row.length; j++) {

                if (row[j].getType() == CellType.DATE) {
                    String[] dateArray = row[j].getContents().trim()
                            .replace("/", "-").split("/");
                    if (dateArray.length == 3) {
                        StringBuilder sb = new StringBuilder()
                                .append(dateArray[0]);
                        sb.append(dateArray[1].length() == 1 ? "-0" : "-")
                                .append(dateArray[1]);
                        sb.append(dateArray[2].length() == 1 ? "-0" : "-")
                                .append(dateArray[2]);
                        rowArray.put(sb);
                        sb = null;
                    } else {
                        rowArray.put(row[j].getContents().trim());
                    }
                } else {
                    rowArray.put(row[j].getContents().trim());
                }
            }

            ja.put(rowArray);
            rowArray = null;
        }
        out.print(ja.toString());

        ja = null;

        book.close();
        iais.close();
        iais = null;
        sheet = null;
        book = null;
        file = null;
        multipartRequest = null;
        out.println("; writeToForm();</script></body></html>");
        out.flush();
        out.close();
        out = null;
        return null;
    }

    /**
     * 查询投资项目预算费用 通过预算编号或者投资项目名称
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView queryYSBHCost(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView(jsonJSP);
        response.setCharacterEncoding("utf-8");

        String operate = request.getParameter("operate");

        if ("1".equals(operate)) {
            String number = request.getParameter("number").replace(" ", "");
            BudgetCostCountDao dao = new BudgetCostCountDao();
            dao.setNumber(number);
            modelAndView.addObject("jsonStr", dao.queryCost());
        } else {
            String number = request.getParameter("number");
            String name = request.getParameter("name");

            if (name != null || number != null) {
                name = java.net.URLDecoder.decode(name, "utf-8");

                number = number.replace(" ", "");
                name = name.replace(" ", "");
                // if ("".equals(number) && "".equals(name)) {
                // modelAndView.addObject("jsonStr",
                // "{success: false, msg : '获取的参数为空，请重试'}");
                // } else {
                // if (number.length() < 4 && name.length() < 4) {
                // modelAndView
                // .addObject("jsonStr",
                // "{success: false, msg : '投资项目预算编号或投资项目名称的长度不能小于4个字符'}");
                // } else {
                BudgetCostNumberDao dao = new BudgetCostNumberDao();
                dao.setName(name);
                dao.setNumber(number);
                modelAndView.addObject("jsonStr", dao.queryCost());
                // }
                // }
            } else {
                modelAndView.addObject("jsonStr",
                        "{success: false, msg : '获取的参数为空，请重试'}");
            }
        }
        return modelAndView;
    }

    /**
     * 通用查询
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commQuery(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView(jsonJSP);
        response.setCharacterEncoding("utf-8");
        User user = AppContext.getCurrentUser();
        response.setCharacterEncoding("utf-8");
        if (user != null) {
            String name = request.getParameter("name");
            String[] args = request.getParameterValues("param");
            boolean safety = true;
            if (MyUtil.strIsNotNull(name)) {
                if (args != null) {
                    String temp = null;
                    for (int i = 0, length = args.length; i < length; i++) {
                        if ("{memberCode}".equals(args[i])) {
                            if (temp == null) {
                                temp = MyOrgManager.getInstance()
                                        .getMemberByID(user.getId()).getCode();
                            }
                            args[i] = temp;
                            temp = null;
                        } else if ("{loginAccount}".equals(args[i])) {
                            if (temp == null) {
                                temp = String.valueOf(user.getLoginAccount());
                            }
                            args[i] = temp;
                            temp = null;
                        } else if (args[i].indexOf("select") > -1
                                || args[i].indexOf("delete") > -1
                                || args[i].indexOf("update") > -1) {
                            safety = false;
                        }

                    }
                }
                if (safety) {
                    modelAndView.addObject("jsonStr", MySQLSetManager
                            .getInstance().query(args, name));
                } else {
                    modelAndView.addObject("jsonStr",
                            "{success:false,msg:'含有非法字段，此查询无效'}");
                }
                args = null;
                name = null;
            } else {
                modelAndView.addObject("jsonStr",
                        "{success:false,msg:'获取参数为空，请重试，或者联系OA系统管理员'}");
            }
            user = null;
        } else {
            modelAndView.addObject("jsonStr",
                    "{success:false,msg:'未获取用户登录信息，请登录后再填写表单'}");
        }
        return modelAndView;
    }

    /**
     * 通用查询SQL设置
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commQuerySet(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView(jsonJSP);
        response.setCharacterEncoding("utf-8");
        User user = AppContext.getCurrentUser();
        if (user != null) {
            if (user.getLoginName().equals("group-admin")) {
                String operate = request.getParameter("operate");
                if ("query".equals(operate)) {
                    modelAndView.addObject("jsonStr", MySQLSetManager
                            .getInstance().getSQLSetList());
                } else if ("look".equals(operate)) {
                    String name = request.getParameter("name").replace(" ", "");
                    modelAndView.addObject("jsonStr", MySQLSetManager
                            .getInstance().look(name));
                } else if ("add".equals(operate) || "change".equals(operate)) {
                    String name = request.getParameter("name").replace(" ", "");
                    String description = java.net.URLDecoder.decode(
                            request.getParameter("description"), "utf-8");
                    String errorMsg = java.net.URLDecoder.decode(
                            request.getParameter("errorMsg"), "utf-8");
                    String nullMsg = java.net.URLDecoder.decode(
                            request.getParameter("nullMsg"), "utf-8");
                    String fieldName = java.net.URLDecoder.decode(
                            request.getParameter("fieldName"), "utf-8");
                    String database = request.getParameter("database").replace(
                            " ", "");
                    List<String> sqlList = Arrays.asList(request
                            .getParameterValues("sql"));

                    if ("add".equals(operate)) {
                        modelAndView.addObject(
                                "jsonStr",
                                MySQLSetManager.getInstance().add(name,
                                        description, errorMsg, nullMsg,
                                        database, fieldName, sqlList));
                    } else if ("change".equals(operate)) {
                        modelAndView.addObject(
                                "jsonStr",
                                MySQLSetManager.getInstance().change(name,
                                        description, errorMsg, nullMsg,
                                        database, fieldName, sqlList));
                    }
                } else if ("del".equals(operate)) {
                    String name = request.getParameter("name").replace(" ", "");
                    modelAndView.addObject("jsonStr", MySQLSetManager
                            .getInstance().del(name));
                }
            } else {
                modelAndView.addObject("jsonStr",
                        "{success:false,msg:'未获得授权，不可以使用此功能'}");
            }
        } else {
            modelAndView.addObject("jsonStr",
                    "{success:false,msg:'未获取用户登录信息，不能使用此功能'}");
        }
        return modelAndView;
    }

    /**
     * 同步设置界面，暂时没有使用
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView tongbu(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = new ModelAndView(jsonJSP);
        response.setCharacterEncoding("utf-8");
        User user = AppContext.getCurrentUser();
        if (user != null) {
            if (user.getLoginName().equals("group-admin")) {
                String operate = request.getParameter("operate");
                if ("accountList".equals(operate)) {
                    // modelAndView.addObject("jsonStr", MySQLSetManager
                    // .getInstance().getSQLSetList());
                }
                // else if ("look".equals(operate)) {
                // String name = request.getParameter("name").replace(" ", "");
                // modelAndView.addObject("jsonStr", MySQLSetManager
                // .getInstance().look(name));
                // } else if ("add".equals(operate) || "change".equals(operate))
                // {
                // String name = request.getParameter("name").replace(" ", "");
                // String description = java.net.URLDecoder.decode(
                // request.getParameter("description"), "utf-8");
                // String errorMsg = java.net.URLDecoder.decode(
                // request.getParameter("errorMsg"), "utf-8");
                // String nullMsg = java.net.URLDecoder.decode(
                // request.getParameter("nullMsg"), "utf-8");
                // String fieldName = java.net.URLDecoder.decode(
                // request.getParameter("fieldName"), "utf-8");
                // String database = request.getParameter("database").replace(
                // " ", "");
                // List<String> sqlList = Arrays.asList(request
                // .getParameterValues("sql"));
                //
                // if ("add".equals(operate))
                // modelAndView.addObject(
                // "jsonStr",
                // MySQLSetManager.getInstance().add(name,
                // description, errorMsg, nullMsg,
                // database, fieldName, sqlList));
                // else if ("change".equals(operate))
                // modelAndView.addObject(
                // "jsonStr",
                // MySQLSetManager.getInstance().change(name,
                // description, errorMsg, nullMsg,
                // database, fieldName, sqlList));
                // } else if ("del".equals(operate)) {
                // String name = request.getParameter("name").replace(" ", "");
                // modelAndView.addObject("jsonStr", MySQLSetManager
                // .getInstance().del(name));
                // }
            } else {
                modelAndView.addObject("jsonStr",
                        "{success:false,msg:'未获得授权，不可以使用此功能'}");
            }
        } else {
            modelAndView.addObject("jsonStr",
                    "{success:false,msg:'未获取用户登录信息，不能使用此功能'}");
        }
        return modelAndView;
    }

    /**
     * 导出Excel
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView expExcel(ModelMap model, HttpServletRequest request) throws Exception {
        AbstractExcelView excelView = null;

        User user = AppContext.getCurrentUser();
        if (user != null) {
            String name = request.getParameter("name");
            String[] args = request.getParameterValues("param");
            boolean safety = true;
            if (MyUtil.strIsNotNull(name)) {
                if (args != null) {
                    String temp = null;
                    for (int i = 0, length = args.length; i < length; i++) {
                        if ("{memberCode}".equals(args[i])) {
                            if (temp == null) {
                                temp = MyOrgManager.getInstance()
                                        .getMemberByID(user.getId()).getCode();
                            }
                            args[i] = temp;
                            temp = null;
                        } else if ("{loginAccount}".equals(args[i])) {
                            if (temp == null) {
                                temp = String.valueOf(user.getLoginAccount());
                            }
                            args[i] = temp;
                            temp = null;
                        } else if (args[i].indexOf("select") > -1
                                || args[i].indexOf("delete") > -1
                                || args[i].indexOf("update") > -1) {
                            safety = false;
                        }

                    }
                }
                if (safety) {
                    excelView = new ZcExcelView(args, name);
                }
                args = null;
                name = null;
            }
            user = null;
        }
        return new ModelAndView(excelView, model);
    }
}
